package com.leyou.gateway.auth.schedu;

import com.leyou.auth.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * User: ycs
 * Date: 2020/9/2
 * Time: 16:46
 * Description: 定时任务获取token
 *
 * @author: ycs
 */
@Slf4j
@Component
public class AppTokenScheduled {
    /**
     * 刷新token的时间(24小时)
     */
    private static final long  TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * 获取失败重试时间(10分钟)
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 存储token
     */
    private String token;

    /**
     * 远程调用服务接口
     */
    @Autowired
    private AuthClient authClient;
    /**
     * 获取服务账号类
     */
    @Autowired
    private JwtProperties jwtProp;

    /**
     * 定时执行获取token
     */
    @Scheduled(fixedRate =TOKEN_REFRESH_INTERVAL)
    public void autoAppAuth(){
        while (true){
            try {
                //获取token
                String token = authClient.
                        authorization(jwtProp.getApp().getId(), jwtProp.getApp().getServiceName());
                this.token=token;
                log.info("【服务获取token成功】");
                //成功获取结束循环
                break;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[{}服务]自定获取token失败,10秒钟后再次尝试获取",jwtProp.getApp().getServiceName());
            }
            //获取失败
            try {
                //睡十秒再试执行循环
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    public String getToken() {
        return token;
    }
}
